/**
 * Copyright (C) 2010 David Simonek <dafesimonek@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddSongsPanel.java
 *
 * Created on Aug 6, 2010, 11:24:41 PM
 */

package org.dafe.partyband.gui.concerts;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.AbstractListModel;
import javax.swing.KeyStroke;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SortOrder;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.dafe.partyband.db.api.IConcert;
import org.dafe.partyband.db.api.handlers.IConcertHandler;
import org.dafe.partyband.db.api.queries.IConcertQuery;
import org.dafe.partyband.db.api.DbManager;
import org.dafe.partyband.gui.Utilities;
import org.dafe.partyband.importer.api.IImporterServices;
import org.dafe.partyband.importer.api.INameEncoder;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import org.jdesktop.swingx.renderer.DefaultListRenderer;
import org.jdesktop.swingx.renderer.StringValue;
import org.jdesktop.swingx.renderer.StringValues;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

/**
 *
 * @author dafe
 */
public class ConcertListPanel extends javax.swing.JPanel {

    private static final IConcertQuery concertQuery = DbManager.getBandManager().getQueriesLookup().lookup(IConcertQuery.class);
    private static final IConcertHandler concertHandler = DbManager.getBandManager().getHandlersLookup().lookup(IConcertHandler.class);
    private static final INameEncoder nameEncoder = Lookup.getDefault().lookup(IImporterServices.class).getNameEncoder();
    private static final Calendar calendar = GregorianCalendar.getInstance();

    List<? extends IConcert> concerts;
    private final Timer searchTimer;
    private final RowFilter<ListModel, Integer> rowFilter;
    private DialogDescriptor descriptor;
    private final ConcertListModel concertsModel;

    /** Creates new form AddSongsPanel */
    public ConcertListPanel() {
        initComponents();

        concerts = new ArrayList<IConcert>(concertQuery.getAllConcerts());

        concertsModel = new ConcertListModel();
        concertList.setModel(concertsModel);
        concertList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        concertList.setAutoCreateRowSorter(true);
        concertList.setHighlighters(HighlighterFactory.createSimpleStriping());
        concertList.setCellRenderer(new DefaultListRenderer(new StringValue() {
            public String getString(Object value) {
                if (value instanceof IConcert) {
                    IConcert concert = (IConcert) value;
                    return Utilities.getConcertString(concert);
                }
                return StringValues.TO_STRING.getString(value);
            }
        }));
        concertList.setComparator(new Comparator<IConcert>() {
            public int compare(IConcert c1, IConcert c2) {
                return c1.getDate().compareTo(c2.getDate());
            }
        });
        concertList.setSortOrder(SortOrder.DESCENDING);
        concertList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                checkValidity();
            }
        });
        concertList.getActionMap().put("DeleteConcertAction", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                IConcert concert = getSelectedConcert();
                Object option = DialogDisplayer.getDefault().notify(new NotifyDescriptor.Confirmation(
                        NbBundle.getMessage(ConcertActionsFactory.class, "MSG_DeleteConcert",
                        Utilities.getConcertString(concert)),
                        NbBundle.getMessage(ConcertActionsFactory.class, "TIT_DeleteConcert")
                ));
                if (!NotifyDescriptor.OK_OPTION.equals(option)) {
                    return;
                }
                concertsModel.removeConcert(concert);
            }
        });
        concertList.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "DeleteConcertAction");

        rowFilter = new RowFilter<ListModel, Integer>() {
            @Override
            public boolean include(Entry<? extends ListModel, ? extends Integer> entry) {
                IConcert concert = concerts.get(entry.getIdentifier());
                String curText = searchField.getText();
                if (curText != null) {
                    curText = nameEncoder.encodeName(curText);
                }
                String location = concert.getLocation();
                if (location != null) {
                    location = nameEncoder.encodeName(location);
                }
                // location match
                if ((location != null && location.indexOf(curText) != -1)) {
                    return true;
                }
                try {
                    int year = Integer.parseInt(curText);
                    calendar.setTime(concert.getDate());
                    return calendar.get(Calendar.YEAR) == year;
                } catch (NumberFormatException ex) {
                    // no operation
                }
                return false;
            }
        };

        searchTimer = new Timer(250, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                concertList.setRowFilter(rowFilter);
                if (concertList.getElementCount() == 1) {
                    concertList.setSelectedIndex(0);
                }
            }
        });
        searchTimer.setRepeats(false);

        searchField.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                searchTimer.restart();
            }

            public void removeUpdate(DocumentEvent e) {
                searchTimer.restart();
            }

            public void changedUpdate(DocumentEvent e) {
                searchTimer.restart();
            }
        });

    }

    public void attachDescriptor (DialogDescriptor descriptor) {
        this.descriptor = descriptor;
        checkValidity();
    }

    @Override
    public void addNotify() {
        super.addNotify();
        searchField.requestFocusInWindow();
    }

    public IConcert getSelectedConcert () {
        int index = concertList.getSelectedIndex();
        if (index != -1) {
            index = concertList.convertIndexToModel(index);
        }
        return index != -1 ? concertsModel.getConcertAt(index) : null;
    }

    private void checkValidity() {
        if (descriptor != null) {
            descriptor.setValid(concertList.getSelectedIndex() != -1);
        }
    }

    private class ConcertListModel extends AbstractListModel {

        public int getSize() {
            return concerts.size();
        }

        public Object getElementAt(int index) {
            return getConcertAt(index);
        }

        public IConcert getConcertAt(int index) {
            return concerts.get(index);
        }

        public void removeConcert(IConcert concert) {
            int index = concerts.indexOf(concert);
            concerts.remove(concert);
            concertHandler.deleteConcert(concert);
            fireIntervalRemoved(this, index, index);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        concertList = new org.jdesktop.swingx.JXList();
        searchField = new javax.swing.JTextField();
        jXLabel1 = new org.jdesktop.swingx.JXLabel();
        jXTitledSeparator1 = new org.jdesktop.swingx.JXTitledSeparator();

        jScrollPane1.setViewportView(concertList);

        searchField.setText(org.openide.util.NbBundle.getMessage(ConcertListPanel.class, "ConcertListPanel.searchField.text", new Object[] {})); // NOI18N

        jXLabel1.setDisplayedMnemonic('H');
        jXLabel1.setLabelFor(searchField);
        jXLabel1.setText(org.openide.util.NbBundle.getMessage(ConcertListPanel.class, "ConcertListPanel.jXLabel1.text", new Object[] {})); // NOI18N

        jXTitledSeparator1.setFont(jXTitledSeparator1.getFont().deriveFont(jXTitledSeparator1.getFont().getStyle() | java.awt.Font.BOLD, jXTitledSeparator1.getFont().getSize()+1));
        jXTitledSeparator1.setTitle(org.openide.util.NbBundle.getMessage(ConcertListPanel.class, "ConcertListPanel.jXTitledSeparator1.title", new Object[] {})); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchField, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
                        .addGap(105, 105, 105))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jXTitledSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jXTitledSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXList concertList;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXLabel jXLabel1;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator1;
    private javax.swing.JTextField searchField;
    // End of variables declaration//GEN-END:variables

}
